package com.trs.publish.task;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.trs.publish.Constants.Constants;
import com.trs.publish.domain.OperationLog;
import com.trs.publish.service.OperationLogService;


@Component
public class OperationLogTask{
	
	private final static Logger logger = LoggerFactory.getLogger(OperationLogTask.class);

	@Autowired
	private OperationLogService operationLogService;
	
	@Scheduled(cron="*/1 * * * * *")
	public void save(){
		//logger.debug("操作日志保存定时任务运行");
		if (!Constants.operationLogQueue.isEmpty()) {
			 saveLog();
		}
	}

	private void saveLog() {
		List<OperationLog> list = new ArrayList<OperationLog>();
		try {
			int count = 0;
			while (!Constants.operationLogQueue.isEmpty() && Constants.operationLogQueue.size() > 0) {
				OperationLog  log = Constants.operationLogQueue.poll();
				if (log != null) {
					list.add(log);
					count++;
					if (count >= 1000) {
						break;
					}
				}
			}
		} catch (Exception e) {
			logger.error("保存操作日志出错：" + e.getMessage());
		}
		
		if (list != null && list.size() > 0) {
			long startTime = System.currentTimeMillis();
			operationLogService.batchInsert(list);
			long endTime = System.currentTimeMillis();
			logger.info("定时任务批量保存操作日志" + list.size() + "条,耗时" + (endTime - startTime) + "毫秒");
		}
	}    
}   